package com.chinaoly.sdk.base;


import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * @创建者 吴斌
 * @创建时间 2018/7/18/018 + 14:04
 * @描述： Fragment 的抽象类，继承SDK 内的 OlyFragment,抽离业务公共逻辑
 */
public abstract class ChinaolyFragment<T extends ViewDataBinding> extends Fragment {

    public T mBinding;
    protected View mView = null;
    //  protected WeakReference<View> mRootView;


    //视图是否加载完毕
    private boolean isViewPrepare = false;

    //数据是否加载过
    private boolean hasLoadData = false;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            int layoutId = getLayoutId();
            if (layoutId != 0) {
                mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
                mView = mBinding.getRoot();
                //mRootView = new WeakReference<View>(mView);
            }
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }
        return mView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewPrepare = true;
        initConfig();
        lazyLoadDataIfPrepared();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            lazyLoadDataIfPrepared();
        }
    }

    private void lazyLoadDataIfPrepared() {
        if (getUserVisibleHint() && isViewPrepare && !hasLoadData) {
            initData();
            hasLoadData = true;
        }
    }


    //加载布局文件
    protected abstract int getLayoutId();

    //加载相关配置属性
    protected abstract void initConfig();

    //具体业务数据处理
    protected abstract void initData();


}
